package mwq.spring.springbucks;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import mwq.spring.springbucks.model.Coffee;
import mwq.spring.springbucks.service.CoffeeService;
import mwq.spring.springbucks.utils.CacheService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;

@Slf4j
@EnableTransactionManagement
@SpringBootApplication
public class SpringBucksDruidsApplication implements ApplicationRunner {
	@Autowired
	CoffeeService coffeeService;
	@Autowired
	CacheService cacheService;

	@Autowired
	private JedisPool jedisPool;

	@Autowired
	private JedisPoolConfig jedisPoolConfig;

	public static void main(String[] args) {
		SpringApplication.run(SpringBucksDruidsApplication.class, args);
	}


	@Bean
	@ConfigurationProperties("redis")
	public JedisPoolConfig jedisPoolConfig() {
		return new JedisPoolConfig();
	}

	@Bean(destroyMethod = "close")
	public JedisPool jedisPool(@Value("${redis.host}") String host) {
		return new JedisPool(jedisPoolConfig(), host);
	}


	@Override
	public void run(ApplicationArguments args) throws Exception {
		//删除所有信息
		coffeeService.removeAllCoffee();

		//遍历插入十条咖啡信息
		Coffee coffee = null;
		for(int i = 0; i<10;i++){
			coffee = new Coffee();
			coffee.setId(Long.parseLong(String.valueOf(i)));
			coffee.setName("coffe"+i );
			coffee.setPrice(Money.of(CurrencyUnit.of("CNY"), 20.0));
			coffeeService.insertCoffee(coffee);
		}
		//打印所有咖啡信息
		log.info("所有咖啡信息：{}",coffeeService.findAll());

		//分页查询 第二页数据 每页五条
		PageInfo<Coffee> coffeePage = coffeeService.findForPage(2,5);
		log.info("第二页的咖啡信息：{}",coffeePage);

		//将结果缓存的redis中
		try (Jedis jedis = jedisPool.getResource()) {
			coffeePage.getList().forEach(c -> {
				jedis.hset("springbucks-menu",
						c.getName(),
						Long.toString(c.getPrice().getAmountMinorLong()));
			});

			Map<String, String> menu = jedis.hgetAll("springbucks-menu");
			log.info("Menu: {}", menu);
		}
	}
}

